using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using WebProject.Models;
using Microsoft.Data.SqlClient;



namespace WebProject.Controllers;

public class ManagerController : Controller
{
    [HttpGet]
    public IActionResult Login()
    {
        return View();
    }


    public string _connectionString = "Server=172.16.73.221;Database=DB;User Id=sa;Password=123456;TrustServerCertificate=True";

    [HttpPost]
    public IActionResult Login(LoginModel model)
    {
        // 检查输入是否为空
        if (string.IsNullOrWhiteSpace(model.Username) || string.IsNullOrWhiteSpace(model.Password))
        {
            return Content("用户名或密码不能为空！");
        }

        // 数据库验证
        if (ValidateUser(model.Username, model.Password))
        {
            // 登录成功
            // return RedirectToAction("Index", "Home");
            return Content("你说得对但是成功登录原神");
        }
        else
        {
            return Content("你说得对但是成功登录鸣潮");
        }
    }


    // 账户密码验证逻辑
    private bool ValidateUser(string username, string password)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            var query = "SELECT COUNT(*) FROM Login WHERE Username = @Username AND Password = @Password";
            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@Username", username);
                command.Parameters.AddWithValue("@Password", password);

                var count = (int)command.ExecuteScalar();
                return count > 0; // 如果查询到数据，则用户存在
            }
        }
    }

    // 查表逻辑
    public ActionResult Index()
    {
        List<StudentModel> students = new List<StudentModel>();

        using (SqlConnection conn = new SqlConnection(_connectionString))
        {
            string query = "SELECT StuNum, StuName, StuAge FROM student";

            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                conn.Open();

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var student = new StudentModel
                        {
                            StuNum = reader.GetInt32(0),
                            StuName = reader.GetString(1),
                            StuAge = reader.GetInt32(2),
                        };

                        students.Add(student);
                    }
                }
            }
        }

        return View(students);
    }

    // 删表按钮
    [HttpPost]
    public ActionResult Delete(int id)
    {
        using (SqlConnection conn = new SqlConnection(_connectionString))
        {
            string query = "DELETE FROM student WHERE StuNum = @StuNum";

            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@StuNum", id);

                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }

        return RedirectToAction("Index");
    }

    // 编辑页面 - 显示指定学生信息
    public IActionResult Edit(int id)
    {
        var student = GetStudentById(id);
        return View(student);
    }

    // 提交更新
    [HttpPost]
    public IActionResult Edit(StudentModel model)
    {
        if (ModelState.IsValid)
        {
            Update(model);
            return RedirectToAction("Index"); // 更新完成后返回列表页面
        }
        return View(model);
    }

    // 获取所有学生
    private IEnumerable<StudentModel> GetAllStudents()
    {
        var students = new List<StudentModel>();
        using (var connection = new SqlConnection(_connectionString))
        {
            string query = "SELECT StuNum, StuName, StuAge FROM Student";
            using (var command = new SqlCommand(query, connection))
            {
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        students.Add(new StudentModel
                        {
                            StuNum = reader.GetInt32(0),
                            StuName = reader.GetString(1),
                            StuAge = reader.GetInt32(2)
                        });
                    }
                }
            }
        }
        return students;
    }

    // 根据 ID 获取单个学生
    private StudentModel GetStudentById(int id)
    {
        StudentModel student = null;
        using (var connection = new SqlConnection(_connectionString))
        {
            string query = "SELECT StuNum, StuName, StuAge FROM Student WHERE StuNum = @id";
            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@id", id);
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        student = new StudentModel
                        {
                            StuNum = reader.GetInt32(0),
                            StuName = reader.GetString(1),
                            StuAge = reader.GetInt32(2)
                        };
                    }
                }
            }
        }
        return student;
    }

    // 更新学生信息
    private void Update(StudentModel model)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            string query = "UPDATE Student SET StuName = @name, StuAge = @age WHERE StuNum = @id";
            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@name", model.StuName);
                command.Parameters.AddWithValue("@age", model.StuAge);
                command.Parameters.AddWithValue("@id", model.StuNum);
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }

    //添加
    [HttpGet]
    public IActionResult Add()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Add(StudentModel model)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            string query = "INSERT INTO Student (StuNum, StuName, StuAge) VALUES (@id, @name, @age)";

            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@id", model.StuNum);
                command.Parameters.AddWithValue("@name", model.StuName);
                command.Parameters.AddWithValue("@age", model.StuAge);

                connection.Open();

                if (command.ExecuteNonQuery() > 0)
                {
                    // 插入成功，跳转到成功页面或显示消息
                    return Content("学生添加成功！");
                }
                else
                {
                    // 插入失败，跳转到错误页面或显示错误消息
                    return Content("学生添加失败！");
                }
            }
        }
    }
}